<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:25%;padding: 0">
      <div class="header">
        <span class="title">{{
          $ct("mdataOrganizationIndex", "组织机构")
        }}</span>
        <span>
          <!-- <a-icon type="more" @click="openOrgView" /> -->
        </span>
      </div>
      <div class="padding-xs">
        <a-input-search
          placeholder="组织机构名称"
          style="width: 100%"
          @search="onSearch"
        />
      </div>
      <div class="body">
        <ZTree
          ref="masterList"
          :loadAll="true"
          :expandAll="false"
          treeText="orgName"
          :columns="columns"
          rowKey="uuid"
          :url="url"
          :parameter="parameter"
          :formatConditions="false"
          :showSearch="false"
          @rowClick="
            (e) => {
              masterRowClick(e);
            }
          "
          @chengTreeData="chengTreeData"
          :isFirst="true"
        >
        </ZTree>
      </div>
    </div>
    <div class="page-common-content">
      <tool-bar
        @search="$refs.subList.refresh(true)"
        @reset="
          () => {
            (subQueryParam = { orgId: subQueryParam.orgId }),
              $refs.subList.refresh(true);
          }
        "
      >
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            :class="selectTree && 'cu-btn-primary'"
            :disabled="!selectTree"
            icon="plus"
            @click="handleAdd()"
            style="margin-right:10px"
          >
            新建岗位
          </a-button>
          <a-button
            icon="download"
            class="cu-btn-primary"
            @click="handleDownloadExcel()"
          >
            下载模版
          </a-button>
          <a-button
            :class="selectTree && 'cu-btn-primary'"
            icon="download"
            @click="handleImport()"
            :disabled="!selectTree"
          >
            导入
          </a-button>
          <!-- <export-data
            fileName="岗位管理"
            fieldInfoUrl="/mdata/sysPosition/getFieldInfo"
            exportUrl="/mdata/sysPosition/exportSysPositionData"
          ></export-data> -->
        </template>
        <template slot="toolForm">
          <a-form-item :label="$ct('postName', '岗位名称')">
            <a-input
              v-model="subQueryParam.positionText"
              :placeholder="$ct('postName', '岗位名称')"
            />
          </a-form-item>
          <a-form-item :label="$ct('postCode', '岗位编码')">
            <a-input
              v-model="subQueryParam.positionCode"
              :placeholder="$ct('postCode', '岗位编码')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        v-if="showPage"
        ref="subList"
        type="sub"
        rowKey="uuid"
        showPagination="auto"
        :url="url"
        :columns="subColumns"
        :queryParam="subQueryParam"
        :showRowSelect="false"
        @rowClick="
          (e) => {
            subRowClick(e);
          }
        "
      >
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a @click="handleEdit(record, $refs.masterList.data, 'sub')">{{
              $ct("edit", "编辑")
            }}</a>
            <span class="action-margin"></span>
            <a
              href="javascript:;"
              @click="handleSub(record, 'sub')"
              class="action-delete"
              >{{ $ct("delete", "删除") }}</a
            >
            <span class="action-margin"></span>
            <!-- <a @click="handleSub(record, 'sub')">用户</a> -->
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="previewUser(record)">岗位成员</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
        <span slot="renderPositionStatus" slot-scope="{ text }">
          <a-tag :color="text === 1 || text === '1' ? 'green' : 'red'">
            {{
              text === 1 || text === "1"
                ? $ct("enable", "启用")
                : $ct("disable", "禁用")
            }}
          </a-tag>
        </span>
      </DataGrid>
      <edit-form
        ref="subModal"
        :visible="subVisible"
        :organization="selectTree"
        :loading="subConfirmLoading"
        :model="subMdl"
        @cancel="handleCancel('sub')"
        @ok="handleOk('sub')"
      />

      <org-preview
        ref="viewOrgModal"
        :visible="viewOrgVisible"
        @cancel="viewOrgVisible = false"
      >
      </org-preview>

      <user-view
        ref="userViewModal"
        v-if="userViewVisible"
        :visible="userViewVisible"
        :uuid="positionUuid"
        :positionText="positionText"
        @close="userViewVisible = false"
      >
      </user-view>

      <!-- 导入弹窗 -->
      <importModal
        :visible.sync="importModalVisible"
        :parameter="selectTree"
      ></importModal>
    </div>
  </div>
</template>
<script>
import { TreeGrid, DataGrid, ZTree, ExportData } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import editForm from "./edit.vue";
import orgPreview from "@/components/TopVUI/custom/orgPreview.vue";
import userView from "./userView";
import importModal from "./importModal";
import { axios } from "@/utils/request";
import { downLoadFileByArraybuffer } from "@/utils/util";

export default {
  mixins: [treeGridMixin],
  components: {
    editForm,
    TreeGrid,
    DataGrid,
    orgPreview,
    ExportData,
    userView,
    // detailModal,
    importModal,
  },
  data() {
    return {
      key: "1",
      selectTree: null,
      columns: [
        {
          title: "组织机构",
          align: "left",
          dataIndex: "text",
        },
      ],
      subColumns: [
        {
          title: "岗位名称",
          dataIndex: "positionText",
          langCode: "postName",
          width: 200,
        },
        {
          title: "岗位编码",
          dataIndex: "positionCode",
          langCode: "postCode",
          width: 250,
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "positionStatus",
          langCode: "state",
          width: 80,
          scopedSlots: {
            customRender: "renderPositionStatus",
          },
        },
        {
          title: "排序",
          align: "center",
          dataIndex: "positionSort",
          langCode: "sort",
          width: 80,
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          width: 150,
          scopedSlots: {
            customRender: "renderAction",
          },
          fixed: "right",
        },
      ],
      masterVisible: false,
      subVisible: false,
      masterConfirmLoading: false,
      subConfirmLoading: false,
      masterMdl: null,
      subMdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      subQueryParam: {},
      url: {
        fathersUrl: "/mdata/organization/getTreeSysOrganizationByOrg",
        expandUrl: "/mdata/organization/getListByPid",
        subList: "/mdata/sysPosition/getPageSet",
        subSave: "/mdata/sysPosition/save",
        subUpdate: "/mdata/sysPosition/update",
        subDelete: "/mdata/sysPosition/deleteBatch",
        getUserPost: "/mdata/sysUserPost/getPageSet",
        savePosition: "/mdata/user/savePosition",
        updatePosition: "/mdata/sysUserPost/update",
        delUserPost: "/mdata/sysUserPost/deleteBatch",
      },
      parameter: {
        father: {
          levelId: 1,
          pid: 1,
        },
        children: {},
      },
      postQueryParam: {},
      visibleDetail: false,
      viewOrgVisible: false,
      userViewVisible: false,
      positionUuid: "",
      positionText: "",
      //
      showPage: false,
      importModalVisible: false,
    };
  },
  filters: {},
  activated() {},
  mounted() {},
  methods: {
    //数组件数据加载完成触发
    chengTreeData(data) {
      let current = data?.[0] ?? {};
      this.selectTree = {
        orgName: current.orgName,
        id: current.id,
      };
      this.subQueryParam.orgId = current.id;
      this.showPage = true;
      setTimeout(() => {
        this.$refs.subList.refresh();
      }, 500);
    },

    //刷新表格
    getRefresh() {
      this.$refs.subList.refresh(true);
    },

    //下载模版
    handleDownloadExcel() {
      axios
        .get(`/mdata/sysPosition/downloadTemplate`, {
          apiType: "file",
          responseType: "arraybuffer",
        })
        .then((res) => {
          downLoadFileByArraybuffer(res, "组织岗位管理模板");
        })
        .catch((_) => {
          this.$message.error("模版下载失败，请稍后重试！");
        });
    },

    //导入
    handleImport() {
      this.importModalVisible = true;
    },

    // 新增
    handleAdd() {
      let form = {};
      this.masterMdl = null;
      form = this.$refs.subModal.form;
      form.resetFields(); // 清理表单数据（可不做）
      this.subVisible = true;
      this.$refs.subModal.title = this.$ct("add", "新增");
      this.subMdl = this.subQueryParam;
      if (this.$refs.subModal.add) this.$refs.subModal.add(this.subMdl);
    },

    masterRowClick(record) {
      this.selectTree = record;
      this.$refs.masterList.rows = record;
      this.subQueryParam.orgId = record.id;
      this.postQueryParam = {};
      this.$refs.subList.refresh();
    },

    subRowClick(record) {
      this.postQueryParam.orgId = record.orgId;
      this.postQueryParam.userNameId = record.userNameId;
    },

    onSearch(value) {
      this.$refs.masterList.data = this.treeFilter(
        value,
        JSON.parse(JSON.stringify(this.$refs.masterList.originalData))
      );
    },

    //树形数据过滤
    treeFilter(value, arr) {
      if (!arr) {
        return [];
      }
      let newarr = [];
      arr.forEach((item) => {
        if (item.orgName.indexOf(value) > -1) {
          let redata = this.treeFilter(value, item.children);
          let obj = {
            ...item,
            children: redata,
          };
          newarr.push(obj);
        } else {
          if (item.children && item.children.length > 0) {
            let redata = this.treeFilter(value, item.children);
            let obj = {
              ...item,
              children: redata,
            };
            if (redata && redata.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    },

    openOrgView() {
      this.viewOrgVisible = true;
      this.$refs.viewOrgModal.getOrgData(this.$refs.masterList.data);
    },

    previewUser(record) {
      this.userViewVisible = true;
      this.positionUuid = record.uuid;
      this.positionText = "岗位成员-【" + record.positionText + "】";
    },
  },
};
</script>

<style scope lang="less">
.page-common-left {
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    color: #606266;
    padding: 10px;
    height: 50px;
    box-sizing: border-box;

    .title {
      font-size: 16px;
    }
  }

  .body {
    padding: 10px;
    overflow: auto;
    flex: 1;
  }
}
</style>
